package com.sec.controller;

import com.sec.dao.mysql.SOtherDao;
import com.sec.domain.mysql.SOther;
import com.sec.domain.mysql.view.OtherView;
import com.sec.util.ConstantUtils;
import com.sec.util.DateJsonValueProcessor;
import com.sec.util.FileUtil;
import com.sec.util.Pager;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.sql.Timestamp;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2017/11/29.
 */
@Controller
@RequestMapping("/articleManager")
public class ArticleController {

    @Resource
    private SOtherDao sOtherDao;

    // 文章主页
    @RequestMapping(value = "/index", method = RequestMethod.GET)
    public String index() {
        return "/article/index.html";
    }

    // 文章详情页
    @RequestMapping(value = "/other_detail")
    public String other_detail(int o_id) {
        return "/article/other_detail.html";
    }

    // 文章删除
    @RequestMapping(value = "/other_delete")
    public String other_delete(int o_id) {
        SOther sOther = sOtherDao.queryById(o_id);
        sOtherDao.delete(sOther);
        return "/article/index.html";
    }

    // 文章添加
    @RequestMapping(value = "/other_add")
    public String other_add() {
        return "/article/other_add.html";
    }

    // 文章图片上传页面
    @RequestMapping(value = "/other_pic")
    public String other_pic(int o_id, String o_pic) {
        return "/article/other_pic.html";
    }

    // 首页分页
    @RequestMapping(value = "/getData",produces = "text/json;charset=UTF-8")
    @ResponseBody
    public String getData(HttpServletRequest request) {
        String limit = request.getParameter("limit");
        String offset = request.getParameter("offset");
        String name = request.getParameter("o_fl");
        String o_mc = request.getParameter("o_mc");
        name = name == null ? "" : name;
        o_mc = o_mc == null ? "" : o_mc;

        Pager pager = new Pager();
        pager.setHql("from OtherView where name like :name and o_mc like :o_mc order by o_rq desc");
        pager.setPage(Integer.parseInt(offset));
        pager.setRows(Integer.parseInt(limit));

        Map<String, Object> params = new HashMap<>();
        params.put("name", "%" + name + "%");
        params.put("o_mc", "%" + o_mc + "%");
        Pager result = sOtherDao.pagerff(pager, params);

        JsonConfig jf = new JsonConfig();
        jf.registerJsonValueProcessor(java.sql.Timestamp.class, new DateJsonValueProcessor("yyyy-MM-dd HH:mm:ss"));
        JSONArray jsonData = new JSONArray();
        if (result.getList() != null && result.getList().size() > 0) {
            List<OtherView> data = (List<OtherView>) result.getList();
            jsonData = JSONArray.fromObject(data, jf);
        }

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("rows", jsonData);//JSONArray
        jsonObject.put("total", pager.getRowsTotal());//总记录数
        return jsonObject.toString();
    }

    // 获取文章详情
    @RequestMapping(value = "/get_other_detail",produces = "text/json;charset=UTF-8")
    @ResponseBody
    public String get_other_detail(int o_id) {
        SOther sOther = sOtherDao.queryById(o_id);

        JsonConfig jf = new JsonConfig();
        jf.registerJsonValueProcessor(java.sql.Timestamp.class, new DateJsonValueProcessor("yyyy-MM-dd HH:mm:ss"));
        JSONObject jsonObject = new JSONObject();
        if(sOther!=null){
            jsonObject = JSONObject.fromObject(sOther, jf);
        }
        return jsonObject.toString();
    }

    // 更新文章信息
    @RequestMapping(value = "/update")
    @ResponseBody
    public String update(HttpServletRequest request) throws IOException {
        // 获取要更新的参数
        String o_id = request.getParameter("o_id");
        String o_mc = request.getParameter("o_mc");
        String o_fl = request.getParameter("o_fl");
        String o_wh = request.getParameter("o_wh");
        String o_nr = request.getParameter("o_nr");

        // 获取要更新的文章信息
        SOther sOther = sOtherDao.queryById(Integer.parseInt(o_id));

        // 更新内容
        sOther.setO_mc(o_mc);
        sOther.setO_fl(Integer.parseInt(o_fl));
        sOther.setO_wh(o_wh);
        sOther.setO_nr(o_nr);
        sOther.setO_rq(new Timestamp(System.currentTimeMillis()));

        // 复制图片文件夹到指定目录下
        String srcPath = request.getSession().getServletContext().getRealPath("/ueditor");
        ConstantUtils constantUtils = new ConstantUtils();
        File src  = new File(srcPath);
        if(src.exists()){
            FileUtil.copyFolder(srcPath, constantUtils.getValue("xjtaxPath") + "/ueditor");
        }

        // 保存
        sOtherDao.update(sOther);
        return "success";
    }

    // 添加文章信息
    @RequestMapping(value = "/add")
    public String add(HttpServletRequest request) throws IOException {
        // 获取要更新的参数
        String o_mc = request.getParameter("o_mc");
        String o_fl = request.getParameter("o_fl");
        String o_wh = request.getParameter("o_wh");
        String o_nr = request.getParameter("o_nr");

        // 获取新的id
        int o_id = getNextId();

        // 更新内容
        SOther sOther = new SOther();
        sOther.setO_id(o_id);
        sOther.setO_mc(o_mc);
        sOther.setO_fl(Integer.parseInt(o_fl));
        sOther.setO_wh(o_wh);
        sOther.setO_nr(o_nr);
        sOther.setO_tj(0);
        sOther.setO_rq(new Timestamp(System.currentTimeMillis()));

        // 复制图片文件夹到指定目录下
        String srcPath = request.getSession().getServletContext().getRealPath("/ueditor");
        ConstantUtils constantUtils = new ConstantUtils();
        File src  = new File(srcPath);
        if(src.exists()){
            FileUtil.copyFolder(srcPath, constantUtils.getValue("xjtaxPath") + "/ueditor");
        }

        // 保存
        sOtherDao.save(sOther);
        return "/article/index.html";
    }

    // * 图片上传
    @RequestMapping(value = "/updateImg")
    public String doFirst(@RequestParam("o_pic") CommonsMultipartFile uploadFile, HttpSession session, HttpServletRequest request) throws IllegalStateException, IOException {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        // 获取文件名作为保存到服务器的文件名称
        if(uploadFile.getSize()>0){
            // 获取参数里的文件名
            String o_id = multipartRequest.getParameter("o_id");
            // 获取文件名
            String fileName = uploadFile.getOriginalFilename();
            if(fileName.endsWith("jpg")||fileName.endsWith("gif")||fileName.endsWith("png")){
                // 前半部分路径，目录，将WebRot下一个名称为images文件夹转换成绝对路径
                String leftPath = session.getServletContext().getRealPath("/images");
                File file = new File(leftPath, fileName);
                uploadFile.transferTo(file);

                // 拷贝文件到指定目录下
                ConstantUtils constantUtils = new ConstantUtils();
                FileUtil.copyFile(file.getAbsolutePath(), constantUtils.getValue("imgPath") + "/" + fileName);
            }
            // 更新数据
            SOther sOther = sOtherDao.queryById(Integer.parseInt(o_id));
            sOther.setO_pic(fileName);
            sOtherDao.update(sOther);
        }
        return "/article/index.html";
    }

    // 获取新的id
    private int getNextId() {
        String hql = "from SOther order by o_id desc";
        List<SOther> sOtherList = sOtherDao.queryListByHql(hql);
        int current_id = 1;
        if(sOtherList!=null && sOtherList.size()>0){
            current_id = sOtherList.get(0).getO_id()+1;
        }
        return current_id;
    }
}
